package com.symria.framework.baidu;

import java.net.URLEncoder;
import java.util.LinkedHashMap;

import com.symria.framework.util.HttpClientUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class DistanceEstimator {

	private static final String URI = "/direction/v1?";
    private static String baidu_url="http://api.map.baidu.com/geocoder/v2/?ak=Q88ZFSOGn78vj8OKYabu63RW&output=json";
	
	public static double route(double srcLat, double srcLon, String srcRegion, double dstLat, double dstLon, String dstRegion){
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("origin", srcLat+","+srcLon);
		map.put("origin_region", srcRegion);
		map.put("destination", dstLat+","+dstLon);
		map.put("destination_region", dstRegion);
		map.put("mode", "walking");
		map.put("output", "json");
		double ret = -1;
		try{
	        String retValue = WebClient.io(URI, map);
		    JSONObject json = JSONObject.fromObject(retValue);
		    if (json.containsKey("status") && json.getInt("status") == 0 && json.containsKey("result")) {
		        JSONObject jsonResult = json.getJSONObject("result");
		        if (jsonResult.containsKey("routes")) {
		            JSONArray jsonRoutes = jsonResult.getJSONArray("routes");
		            if (jsonRoutes.size() > 0) {
		                ret = jsonRoutes.getJSONObject(0).getInt("distance") / 1000.0;
		            }
		        }
		    }
		}catch(Exception e){
		    e.printStackTrace();
		}
		return ret;
	}
	public static JSONObject parseLatLon(String city,String address){
		
		try{
			baidu_url+=("&address="+URLEncoder.encode(address, "UTF-8"));
			baidu_url+=("&city="+URLEncoder.encode(city, "UTF-8"));
			String json = HttpClientUtils.readFromURL(baidu_url,null);
			JSONObject o = JSONObject.fromObject(json).getJSONObject("result").getJSONObject("location");
			//System.out.println(o.getDouble("lng"));
			//System.out.println(o.getDouble("lat"));
			return o;
		}catch(Exception e){
			return null;
		}
	}
	public static void main(String[] args){
		parseLatLon("龙岩", "永定区电力大厦");
	}
	
	
}
